package game.Menus;

import game.ActionListener;

import java.util.ArrayList;

import org.newdawn.slick.Image;
import org.newdawn.slick.geom.Vector2f;

/**
 * This class represent an advanced menu. 
 * The meaning of this is that this menu contains a marker showing which item is selected.
 * @author Sebastian Isheden and Victor Beer.
 *
 */
public class AdvancedMenu {
	private ArrayList<AdvancedMenuItem> items = new ArrayList<AdvancedMenuItem>();
	private MenuMarker marker;
	private int index;
	private float gap;
	
	/**
	 * Creates a new AdvancedMenu
	 * @param menuMarkerImage The image of the marker.
	 * @param menuMarkerHeight The height of the marker.
	 * @param gap THe gap between items in the menu.
	 */
	public AdvancedMenu(Image menuMarkerImage, float menuMarkerHeight, float gap) {
		this.marker = new MenuMarker(menuMarkerImage.copy(), menuMarkerHeight);
		this.gap = gap;
	}
	
	/**
	 * Updates the menu.
	 * @param delta The time in millisecound since the last update.
	 */
	public void update(int delta) {
		this.marker.update(delta);
	}
	
	/**
	 * Sets the current index(the item in the menu which is selected)
	 * @param index The new index.
	 */
	public void setMenuIndex(int index) {
		if(index >= items.size() || index < 0) {
			index = 0;
		}
		
		this.index = index;
		this.marker.change(getCurrentItem().getPosition(), getCurrentItem().getImageWidth());
	}
	
	private AdvancedMenuItem getCurrentItem() {
		return items.get(index);
	}
	
	/**
	 * Adds an item to the menu.
	 * @param itemImage The image of the item.
	 * @param action The action the item will perforemed when used.
	 */
	public void AddItem(Image itemImage, ActionListener action) {
		Vector2f newPosition = new Vector2f(getWidth() + this.gap, 0);
		items.add(new AdvancedMenuItem(itemImage, newPosition, action));
		
		if(items.size() == 1) { //first item added
			marker.change(getCurrentItem().getPosition(), getCurrentItem().getImageWidth());
		}
	}
	
	/**
	 * Returns the width of the advanced menu.
	 */
	public float getWidth() {
		float width = -this.gap;
		for(AdvancedMenuItem item : items) {
			width += item.getImageWidth() + this.gap;
		}
		
		return width;
	}
	
	/**
	 * Renders the menu with the left top corner at position.
	 * @param position
	 */
	public void draw(Vector2f position) {
		this.marker.draw(position);
		for(AdvancedMenuItem item : items) {
			item.print(position);
		}
	}
}
